﻿using System.Windows;
using System.Windows.Media;

namespace XEvolve.Presentation.Extensions
{
    public static class DependencyObjectExtensions
    {
        public static ChildType FindChild<ChildType>(this DependencyObject target) where ChildType : DependencyObject
        {
            var childrenCount = VisualTreeHelper.GetChildrenCount(target);
            for (var i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(target, i);
                if (child is ChildType || child == null) return child as ChildType;
                var grandchild = child.FindChild<ChildType>();
                if (grandchild != null) return grandchild;
            }
            return null;
        }

        public static AncestorType FindAncestor<AncestorType>(this DependencyObject target) where AncestorType : DependencyObject
        {
            var parent = VisualTreeHelper.GetParent(target);
            if (parent == null) return null;
            if (parent is AncestorType) return (AncestorType) parent;
            return parent.FindAncestor<AncestorType>();
        }
    }
}